<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in arr" :key="item.id">
          <td>{{ index + 1 }}</td>
          <td>{{ item.uname }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="del(item.id)">删除</button>
            <button @click="cun(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
// 一定一定要记得 数据驱动视图
export default {
  data() {
    return {
      id:'',
      uname:'',
      age:"",
      gender:"",
      isEdit:true,
      arr: [
        {
          id: 1,
          uname: 1,
          age: 20,
          gender: "男",
        },
        {
          id: 2,
          uname: 3,
          age: 15,
          gender: "女",
        },
      ],
    };
  },
  methods: {
    // 添加
    add(){
      // 表单验证
     if (this.uname && this.age && this.gender) {
      // 判断是点击添加还是修改,true为添加，反之修改
       if (this.isEdit) {
        const newObj ={
          id:+new Date(),
          uname:this.uname,
          age:this.age,
          gender:this.gender
        }
        this.arr.push(newObj)
        this.uname ='',
        this.age = "",
        this.gender = ""
        this.isEdit = true
      }else{
        this.isEdit = true
        this.arr.map((item) =>{
          if (item.id === this.id) {
            item.uname = this.uname,
            item.age = this.age,
            item.gender = this.gender
          }
        })
      }
      this.id = ""
      this.uname = "",
      this.gender ="",
      this.age = ""
     }
    },
    // 修改
    cun(id){
      // 
      this.isEdit = false
      // find 找到满足条件的这个值并停止循环并返回
      const obj = this.arr.find((item) => item.id === id)
      this.uname = obj.uname,
      this.age = obj.age,
      this.gender = obj.gender
      this.id = obj.id
    },
    // 删除
    del(id){
      console.log(id);
      // filter 过滤数组，将不符合的过滤掉。符合的就返回。
      this.arr = this.arr.filter((item) => {
        console.log(item.id);
        return item.id !== id})
    }
    }
  }
</script>
